package com.CommunityHub.kiana.controller;



import com.CommunityHub.kiana.po.ResidenceInfo;
import com.CommunityHub.kiana.po.ServiceRecord;
import com.CommunityHub.kiana.po.ServiceResidence;
import com.CommunityHub.kiana.po.User;
import com.CommunityHub.kiana.service.MemberService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/ServiceHistoryServlet")
public class ServiceHistoryServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("user") == null) {
            response.sendRedirect("login.jsp");
            return;
        }

        User user = (User) session.getAttribute("user");
        int memberId = user.getId();

        MemberService memberService = new MemberService();
        List<ResidenceInfo> occupants = null;
        try {
            occupants = memberService.getOccupants(memberId);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        request.setAttribute("occupants", occupants);
        try {
            List<ServiceResidence> serviceHistory = memberService.getServiceHistoryById(memberId);
            request.setAttribute("serviceHistory", serviceHistory);

            request.getRequestDispatcher("serviceHistory.jsp").forward(request, response);
        } catch (SQLException e) {
            request.setAttribute("error", "加载服务记录失败: " + e.getMessage());
            request.getRequestDispatcher("serviceHistory.jsp").forward(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
